package com.xj.common.base.common.util;
import java.io.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xj.common.bussiness.deviceJpg.entity.TbDeviceJpg;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * 图片上传工具类
 */
public class ImageUploadUtil {
	 // 图片类型
    private static List<String> fileTypes = new ArrayList<String>();

    static {
        fileTypes.add(".jpg");
        fileTypes.add(".jpeg");
        fileTypes.add(".bmp");
        fileTypes.add(".gif");
        fileTypes.add(".png");
        fileTypes.add(".mp4");
    }

    /**
     * 图片上传
     * 
     * @Title upload
     * @param request
     *            文件上传目录：比如upload(无需带前面的/) upload/news ..
     * @return
     * @throws IllegalStateException
     * @throws IOException
     * @return Map<String,String>
     *     返回对应的字段和地址的字符串
     */
    public static Map<String,String> upload(HttpServletRequest request, String title) throws IllegalStateException,
            IOException {

        //如上传的本地文件为c://user/text.jpg文件
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
                .getServletContext());
        // 图片名称
        String fileName = null;
        // 判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            Map<String,String> imgType = new HashMap<String,String>();
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 记录上传过程起始时的时间，用来计算上传时间
                // int pre = (int) System.currentTimeMillis();

                // 取得上传文件名text.jpg
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null) {
                    //取得当前文件上传name值
                    String imgName = file.getName();
                    // 取得当前上传文件的文件原名c://user/text.jpg
                    String myFileName = file.getOriginalFilename();
                    // 如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if (myFileName.trim() != "") { //删除原始文件名的前后空格可有可无，为了更严格的判断加入
                        // 获得图片的原始名称
                        String originalFilename = file.getOriginalFilename();
                        // 获得图片后缀名称,如果后缀不为图片格式，则不上传
                        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase(); //截取文件后缀并保证其为小写
                        if (!fileTypes.contains(suffix)) { //匹配文件格式是否为图片
                            continue;
                        }
                        // 获得上传路径的绝对路径地址(/upload)-->
                        String realPath = request.getSession().getServletContext().getRealPath("/"+title+"/");
                        System.out.println("上传的绝对地址"+realPath);
                        // 如果路径不存在，则创建该路径
                        File realPathDirectory = new File(realPath);
                        if (realPathDirectory == null || !realPathDirectory.exists()) {
                            realPathDirectory.mkdirs();
                        }
                        System.out.println(title);
                        // 重命名上传后的文件名 111112323.jpg
                        fileName = imgName + suffix;
                        // 定义上传路径 .../upload/111112323.jpg
                        File uploadFile = new File(realPathDirectory + "/" + fileName);
                        System.out.println(uploadFile);
                        file.transferTo(uploadFile);
                    }
                    imgType.put(imgName,fileName);
                    return imgType;
                }
                // 记录上传该文件后的时间
                // int finaltime = (int) System.currentTimeMillis();
                // System.out.println(finaltime - pre);
            }
        }
        return null;
    }

    /**
     * ckeditor文件上传功能，回调，传回图片路径，实现预览效果。
     * 
     * @Title ckeditor
     * @param request
     * @param response
     * @param DirectoryName
     *            文件上传目录：比如upload(无需带前面的/) upload/..
     * @throws IOException
     */
    public static void ckeditor(HttpServletRequest request, HttpServletResponse response, String DirectoryName)
            throws IOException {
        Map<String, String> fileNames = upload(request, DirectoryName);
        String fileName=null;
        PrintWriter out = response.getWriter();
        for (Map.Entry<String, String> entry : fileNames.entrySet()) {
            fileName = entry.getValue();
            // 结合ckeditor功能
            // imageContextPath为图片在服务器地址，如upload/123.jpg,非绝对路径
            String imageContextPath = request.getContextPath() + "/" + DirectoryName + "/" + fileName;
            response.setContentType("text/html;charset=UTF-8");
            String callback = request.getParameter("CKEditorFuncNum");
            out.println("<script type=\"text/javascript\">");
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + imageContextPath + "',''" + ")");
            out.println("</script>");
        }
        out.flush();
        out.close();
    }

    public static String uploadImg(String imageType, MultipartHttpServletRequest multiReq) throws IllegalStateException {
        Iterator<String> iter = multiReq.getFileNames();
        System.out.println(iter.hasNext());
        while (iter.hasNext()) {
            // 记录上传过程起始时的时间，用来计算上传时间
            // int pre = (int) System.currentTimeMillis();

            // 取得上传文件名text.jpg
            MultipartFile file = multiReq.getFile(iter.next());
            if (file != null) {


                //取得当前文件上传name值
                String imgName = file.getName();
                System.out.println("上传的文件名字："+imgName);

                // 获得图片的原始名称
                String uploadFilePath = file.getOriginalFilename();
                // 获得图片后缀名称,如果后缀不为图片格式，则不上传
                String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.lastIndexOf(".")).toLowerCase(); //截取文件后缀并保证其为小写
                if (!fileTypes.contains(uploadFileSuffix)) { //匹配文件格式是否为图片
                    continue;
                }
                FileOutputStream fos = null;
                FileInputStream fis = null;
                try {
                    //获取文件需要上传到的路径
                    //String path="d://uploadFiles//";
                    String path="/usr/docker/images/"+imageType;
                    System.out.println("上传的绝对地址："+path);
                    fis = (FileInputStream) file.getInputStream();
                    File fil=new File(path);
                    if (fil == null || !fil.exists()) {
                        fil.mkdirs();
                        System.out.println("创建文件夹成功");
                    }
                    //时间戳
                    long timestamp=System.currentTimeMillis();
                    fos = new FileOutputStream(fil+"/" +imgName+timestamp+uploadFileSuffix);
                    byte[] temp = new byte[1024];
                    int i = fis.read(temp);
                    while (i != -1){

                        fos.write(temp,0,temp.length);
                        fos.flush();
                        i = fis.read(temp);
                    }

                    String jpgPath="https://www.gcjxglzx.com/images/"+imageType+"/"+imgName+timestamp + uploadFileSuffix;
                    System.out.println("0.0.0.0++++++++++++++++"+jpgPath);
                    return jpgPath;
                }catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } //http://119.23.111.186/jpg/
            }
            return null;
        }
        return null;
    }
}